/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 */

import fse from 'fs-extra';
import { FileSet } from '@ohos/hvigor';

import { CompileResourceBuildCommandType } from '../utils/compile-resources-util.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';
import { resolveHookDependency } from '../utils/task-util.js';

import { AbstractCompileResource } from './abstract/abstract-compile-resource.js';
import { TaskNames } from './common/task-names.js';
import { ModuleTargetData } from './data/hap-task-target-data.js';
import { TargetTaskService } from './service/target-task-service.js';
import Task = TaskNames.Task;

/**
 * prview场景增量方式编译资源
 *
 * @since 2022/09/22
 */
export class PreviewCompileResource extends AbstractCompileResource {
  protected processProfileTask: string;
  private _log: OhosLogger = OhosLogger.getLogger(PreviewCompileResource.name);

  declareExecutionCommand(): string {
    return this.compileCommands!.toString();
  }

  constructor(targetTaskService: TargetTaskService) {
    super(targetTaskService, Task.PREVIEW_COMPILE_RESOURCE);
    this.generateSourceRDir = this.pathInfo.getGenerateSourceR();
    this.processProfileTask = Task.PREVIEW_PROCESS_RESOURCE.name;
  }

  initTaskDepends() {
    this.declareDepends(resolveHookDependency(Task.PREVIEW_PROCESS_RESOURCE.name, this.targetName));
  }

  declareInputFiles(): FileSet {
    const mergedModuleJson = this.targetService.getTargetData().getPathInfo().getIntermediatesMergeProfile();
    if (fse.existsSync(mergedModuleJson)) {
      return super.declareInputFiles().addEntry(mergedModuleJson);
    }
    return super.declareInputFiles();
  }

  async doTaskAction() {
    await this.compilationProcess(CompileResourceBuildCommandType.COMMAND, this.targetData);
  }

  async invokeRestool(targetData: ModuleTargetData): Promise<void> {
    await this.previewCompileLink(this._log, () => {
      this.replaceTargetPages(targetData, this._log);
    });
  }
}
